import React, { Component } from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'

import './List.css'

export default class List extends Component {
  static propTypes = {
    keywords: PropTypes.string.isRequired
  }

  state = {
    // 是否第一次查询
    initQuery: true,
    loading: false,
    userList: [],
    failed: false
  }

  componentWillReceiveProps(newProp) {
    // 更改状态为搜索中
    this.setState({
      initQuery: false,
      loading: true
    })
    // 请求地址
    const url = `https://api.github.com/search/users?q=${newProp.keywords}`
    axios.get(url)
      .then((response) => {
        const result = response.data;
        
        this.setState({
          userList: result.items.map(user => (
            {
              name: user.login,
              pic: user.avatar_url,
              html_url: user.html_url
            }
          )),
          loading: false,
          failed: false
        })
      })
      .catch((error) => {
        this.setState({
          failed: true,
          loading: false
        })
      })
  }
  render() {
    const { initQuery, loading, userList, failed } = this.state;
    if (initQuery) {
      return <h1>请输入用户名进行搜索</h1>
    } else if (loading) {
      return <h1>加载中</h1>
    } else if (failed) {
      return <h1>搜索失败</h1>
    } else {
      return (
        <div className="row">
          {
            userList.map(user => (
              <div className="card" key={user.name}>
                <a href={user.html_url} target="blank">
                  <img src={user.pic} alt={user.name} style={{ width: 100 }} />
                </a>
                <p className="card-text">{user.name}</p>
              </div>
            ))
          }
        </div>
      )
    }

  }
}
